package davidandroidprojecttools.qq986945193.com.davidandroidprojecttools.phone;

import android.app.AlertDialog;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.media.SoundPool;
import android.os.Handler;
import android.os.Looper;
import android.os.SystemClock;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import davidandroidprojecttools.qq986945193.com.davidandroidprojecttools.R;
import davidandroidprojecttools.qq986945193.com.davidandroidprojecttools.activity.BaseActivity;
import davidandroidprojecttools.qq986945193.com.davidandroidprojecttools.adapter.MyAdapter_CommonAdapter;
import davidandroidprojecttools.qq986945193.com.davidandroidprojecttools.app.MyApplication;
import davidandroidprojecttools.qq986945193.com.davidandroidprojecttools.app.ViewHolder;
import davidandroidprojecttools.qq986945193.com.davidandroidprojecttools.callback.OkHttpStopCallback;
import davidandroidprojecttools.qq986945193.com.davidandroidprojecttools.phone.contants.Url;
import davidandroidprojecttools.qq986945193.com.davidandroidprojecttools.phone.entity.CallPhoneDetail;
import davidandroidprojecttools.qq986945193.com.davidandroidprojecttools.phone.entity.JianpanEntity;
import davidandroidprojecttools.qq986945193.com.davidandroidprojecttools.phone.entity.RestModel;
import davidandroidprojecttools.qq986945193.com.davidandroidprojecttools.utils.BigDecimalUtil;
import davidandroidprojecttools.qq986945193.com.davidandroidprojecttools.utils.LogUtil;
import davidandroidprojecttools.qq986945193.com.davidandroidprojecttools.utils.ToastUtils;
import okhttp3.Request;
import okhttp3.Response;

/**
 * @author ：程序员小冰
 * @新浪微博 ：http://weibo.com/mcxiaobing
 * @GitHub: https://github.com/QQ986945193
 * @CSDN博客: http://blog.csdn.net/qq_21376985
 * @交流Qq ：986945193
 */

/**
 *
 */
public class JianpanActivity extends BaseActivity {
    private ListView lv_jianpan;
    private TextView tv_input;
    private ImageView btn_one;
    private ImageView btn_three;
    private ImageView btn_two;
    private ImageView btn_four;
    private ImageView btn_five;
    private ImageView btn_six;
    private ImageView btn_seven;
    private ImageView btn_eight;
    private ImageView btn_nine;
    private ImageView btn_call;
    private ImageView btn_zero;
    private ImageView btn_del;
    private ImageView btn_xing;
    private ImageView btn_jing;

    /**
     * 是否显示键盘。true显示，false不显示
     */
    private boolean isShowJianPan = true;

    private String inputStr = "";

    private ImageView btn_hidden_jianpan;

    private LinearLayout ll_jiugongge;

    private Map<String, String> params;

    @Override
    protected void initView() {
        setContentView(R.layout.activity_jianpan);
        lv_jianpan = (ListView) findViewById(R.id.lv_jianpan);
        btn_one = (ImageView) findViewById(R.id.btn_one);
        btn_three = (ImageView) findViewById(R.id.btn_three);
        btn_two = (ImageView) findViewById(R.id.btn_two);
        btn_four = (ImageView) findViewById(R.id.btn_four);
        btn_five = (ImageView) findViewById(R.id.btn_five);
        btn_six = (ImageView) findViewById(R.id.btn_six);
        btn_seven = (ImageView) findViewById(R.id.btn_seven);
        btn_eight = (ImageView) findViewById(R.id.btn_eight);
        btn_nine = (ImageView) findViewById(R.id.btn_nine);
        btn_zero = (ImageView) findViewById(R.id.btn_zero);
        btn_call = (ImageView) findViewById(R.id.btn_call);
        tv_input = (TextView) findViewById(R.id.tv_input);
        btn_del = (ImageView) findViewById(R.id.btn_del);
        btn_hidden_jianpan = (ImageView) findViewById(R.id.btn_hidden_jianpan);
        ll_jiugongge = (LinearLayout) findViewById(R.id.ll_jiugongge);
        btn_xing = (ImageView) findViewById(R.id.btn_xing);
        btn_jing = (ImageView) findViewById(R.id.btn_jing);

        if (isShowJianPan) {
            ll_jiugongge.setVisibility(View.VISIBLE);
        } else {
            ll_jiugongge.setVisibility(View.GONE);
        }

        params = new HashMap<>();

        initSound();
    }


    private List<JianpanEntity.DataBean> mDataList = new ArrayList<>();
    private MyCommonAdapter adapter;

    @Override
    protected void initData() {
        adapter = new MyCommonAdapter(JianpanActivity.this, mDataList);
        lv_jianpan.setAdapter(adapter);
        lv_jianpan.setDivider(null);
        getData();
    }

    @Override
    protected void setOnclickListener() {
        btn_one.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getClickTextNum("1");


            }
        });
        btn_two.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getClickTextNum("2");
            }
        });
        btn_three.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getClickTextNum("3");
            }
        });
        btn_four.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getClickTextNum("4");
            }
        });
        btn_five.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getClickTextNum("5");
            }
        });
        btn_six.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getClickTextNum("6");

            }
        });
        btn_seven.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getClickTextNum("7");

            }
        });
        btn_eight.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getClickTextNum("8");
            }
        });
        btn_nine.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getClickTextNum("9");

            }
        });
        btn_zero.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getClickTextNum("0");

            }
        });
        btn_xing.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getClickTextNum("*");

            }
        });
        btn_jing.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getClickTextNum("#");

            }
        });

        btn_call.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (TextUtils.isEmpty(inputStr)) {
                    ToastUtils.show(JianpanActivity.this, "输入的号码不能为空", Toast.LENGTH_LONG);
                    return;
                }


                if (inputStr.equals("##21#")) {

                    new Handler().postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            // 延迟执行taost
                            Handler mainHandler = new Handler(Looper.getMainLooper());
                            mainHandler.post(new Runnable() {
                                @Override
                                public void run() {
                                    //获取布局xml
                                    View tempView = LayoutInflater.from(JianpanActivity.this).inflate(R.layout.login_message, null);
                                    TextView textView = (TextView) tempView.findViewById(R.id.error);
                                    //添加需要显示的信息
                                    textView.setText("来电转接 删除成功");

                                    Toast toast = new Toast(JianpanActivity.this);
                                    //显示在屏幕的中间
                                    toast.setGravity(Gravity.CENTER, 0, 0);
                                    toast.setDuration(Toast.LENGTH_LONG);
                                    toast.setView(tempView);
                                    toast.show();
                                    inputStr = "";
                                    lv_jianpan.setVisibility(View.VISIBLE);
                                    tv_input.setVisibility(View.GONE);
                                    tv_input.setText(inputStr);
                                    getData();

                                    return;
                                }
                            });
                            return;
                        }
                    }, 2000); //5秒


                } else if (inputStr.contains("*") || inputStr.contains("#")) {
                    ToastUtils.show(JianpanActivity.this, "电话号码不正确", Toast.LENGTH_LONG);
                    return;
                } else if (inputStr.length() != 11) {
                    ToastUtils.show(JianpanActivity.this, "电话号码不正确", Toast.LENGTH_LONG);

                    return;
                } else {
                    params.put("callPhoneNum", inputStr);
                    params.put("userId", MyApplication.getApp().getSN());

                    okHttpUtils.post(Url.PHONE_BASE_URL + "/call-phone-info/add", params, null, new OkHttpStopCallback<CallPhoneDetail>() {

                        @Override
                        public void onSuccess(Response response, CallPhoneDetail entity) {
                            if (entity != null) {
                                CallPhoneDetail.DataBean data = entity.getData();
                                if (entity.getCode() == 200 && data != null) {
                                    // 跳转
                                    inputStr = "";

                                    Intent intent = new Intent(JianpanActivity.this, CallActivity.class);
                                    intent.putExtra("id", String.valueOf(data.getId()));
                                    intent.putExtra("callPhoneAddress", data.getCallPhoneAddress());
                                    intent.putExtra("callPhoneNum", data.getCallPhoneNum());
                                    startActivity(intent);
                                }

                            }


                        }

                        @Override
                        public void onFailure(Request request, Exception e) {
                            super.onFailure(request, e);
                            e.printStackTrace();
                        }

                        @Override
                        public void onError(Response response, int code, Exception e) {
                            super.onError(response, code, e);
                            e.printStackTrace();
                        }
                    });
                }


            }
        });


        lv_jianpan.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                // 这里直接拨出，右边图标是进入详情
                params.put("callPhoneNum",  mDataList.get(position).getCallPhoneNum());
                params.put("userId", MyApplication.getApp().getSN());

                okHttpUtils.post(Url.PHONE_BASE_URL + "/call-phone-info/add", params, null, new OkHttpStopCallback<CallPhoneDetail>() {

                    @Override
                    public void onSuccess(Response response, CallPhoneDetail entity) {
                        if (entity != null) {
                            CallPhoneDetail.DataBean data = entity.getData();
                            if (entity.getCode() == 200 && data != null) {
                                // 跳转
                                inputStr = "";

                                Intent intent = new Intent(JianpanActivity.this, CallActivity.class);
                                intent.putExtra("id", String.valueOf(data.getId()));
                                intent.putExtra("callPhoneAddress", data.getCallPhoneAddress());
                                intent.putExtra("callPhoneNum", data.getCallPhoneNum());
                                startActivity(intent);
                            }

                        }


                    }

                    @Override
                    public void onFailure(Request request, Exception e) {
                        super.onFailure(request, e);
                        e.printStackTrace();
                    }

                    @Override
                    public void onError(Response response, int code, Exception e) {
                        super.onError(response, code, e);
                        e.printStackTrace();
                    }
                });

            }
        });

        lv_jianpan.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> adapterView, View view, final int position, long l) {
                AlertDialog.Builder builder = new AlertDialog.Builder(JianpanActivity.this);
                builder.setTitle("温馨提示！");
                builder.setMessage("确定删除？");
                builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        boolean isSuccess;
                        // 删除listView选择item的同时删除数据库中对应的信息
                        params.put("id", String.valueOf(mDataList.get(position).getId()));
                        params.put("userId",MyApplication.getApp().getSN());
                        okHttpUtils.post(Url.PHONE_BASE_URL + "/call-phone-info/del", params, null, new OkHttpStopCallback<RestModel>() {

                            @Override
                            public void onFailure(Request request, Exception e) {
                                super.onFailure(request, e);
                                e.printStackTrace();
                                Toast.makeText(JianpanActivity.this, "删除失败", Toast.LENGTH_LONG).show();
                                return;

                            }

                            @Override
                            public void onSuccess(Response response, RestModel entity) {
                                if (entity != null && 200 == entity.getCode()) {
                                    Toast.makeText(JianpanActivity.this, "删除成功", Toast.LENGTH_LONG).show();
                                    getData();
                                    return;
                                }
                            }

                            @Override
                            public void onError(Response response, int code, Exception e) {
                                super.onError(response, code, e);
                                e.printStackTrace();
                            }
                        });


                    }
                }).setNegativeButton("取消", null);
                builder.create().show();
                // 返回true避免与点击事件冲突
                return true;
            }
        });


        btn_del.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                if (TextUtils.isEmpty(inputStr) || inputStr.length() <= 0) {
                    // 输入的内容为空了。则键盘显示，listView显示，
                    inputStr = "";
                    lv_jianpan.setVisibility(View.VISIBLE);
                    tv_input.setVisibility(View.GONE);
                    tv_input.setText(inputStr);
                    getData();
                    return;
                }

                if (inputStr.length() == 1) {
                    // 输入的内容为空了。则键盘显示，listView显示，
                    inputStr = "";
                    lv_jianpan.setVisibility(View.VISIBLE);
                    tv_input.setVisibility(View.GONE);
                    tv_input.setText(inputStr);
                    getData();
                    return;
                }

                // 不为空，则截取最后一位
                inputStr = inputStr.substring(0, inputStr.length() - 1);

                lv_jianpan.setVisibility(View.GONE);
                tv_input.setVisibility(View.VISIBLE);
                tv_input.setText(inputStr);

            }
        });

        btn_hidden_jianpan.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isShowJianPan) {
                    isShowJianPan = false;
                    ll_jiugongge.setVisibility(View.GONE);

                    ViewGroup.LayoutParams para;
                    para = lv_jianpan.getLayoutParams();
                    para.height = 800;
                    lv_jianpan.setLayoutParams(para);


                } else {
                    ll_jiugongge.setVisibility(View.VISIBLE);
                    isShowJianPan = true;
                    ViewGroup.LayoutParams para;
                    para = lv_jianpan.getLayoutParams();
                    para.height = 210;
                    lv_jianpan.setLayoutParams(para);

                }
            }
        });
    }

    private void getClickTextNum(String s) {
        playSound();

        if (TextUtils.isEmpty(inputStr)) {
            inputStr = s;
            lv_jianpan.setVisibility(View.INVISIBLE);
            tv_input.setVisibility(View.VISIBLE);
            tv_input.setText(inputStr);
            return;
        }

        lv_jianpan.setVisibility(View.INVISIBLE);
        tv_input.setVisibility(View.VISIBLE);
        inputStr += s;
        tv_input.setText(inputStr);
    }

    private void getData() {

//        List<JianpanEntity> list = new ArrayList<>();
//        for (int i = 0; i < 3; i++) {
//            JianpanEntity jianpanEntity = new JianpanEntity();
//            jianpanEntity.setPhoneNum("15090636764");
//            jianpanEntity.setFromAddress("上海 移动");
//            jianpanEntity.setMinute(String.valueOf(i));
//            jianpanEntity.setTime("20:03");
//            list.add(jianpanEntity);
//        }
//        mDataList.clear();
//        mDataList.addAll(list);
//        adapter.notifyDataSetChanged();


        okHttpUtils.get(Url.PHONE_BASE_URL + "/call-phone-info/list?userId=" + MyApplication.getApp().getSN(), null, new OkHttpStopCallback<JianpanEntity>() {

            @Override
            public void onSuccess(Response response, JianpanEntity entity) {
                if (entity != null) {
                    if (entity.getCode() == 200 && entity.getData() != null) {
                        mDataList.clear();
                        mDataList.addAll(entity.getData());
                        adapter.notifyDataSetChanged();
                    }
                }

            }

            @Override
            public void onFailure(Request request, Exception e) {
                super.onFailure(request, e);
            }
        });

    }

    class MyCommonAdapter extends MyAdapter_CommonAdapter<JianpanEntity.DataBean> {
        private List<JianpanEntity.DataBean> lists = new ArrayList<>();

        public MyCommonAdapter(Context context, List<JianpanEntity.DataBean> datas) {
            super(context, datas);
            this.lists.clear();
            this.lists.addAll(datas);

        }

        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
            ViewHolder holder = ViewHolder.getHolder(mContext, convertView, parent,
                    R.layout.item_listview_jianpan, position);
            final JianpanEntity.DataBean bean = mDatas.get(position);

            TextView tv_phone_number;
            TextView tv_gray;
            TextView tv_address;
            ImageView iv_call_right;

            tv_phone_number = holder.getView(R.id.tv_phone_number);
            tv_address = holder.getView(R.id.tv_address);
            tv_gray = holder.getView(R.id.tv_gray);
            iv_call_right = holder.getView(R.id.iv_call_right);

            if (bean.getCallPhoneNum().length() < 11 || bean.getCallPhoneNum().length() > 11) {
                tv_phone_number.setText(bean.getCallPhoneNum());
            } else {
                StringBuffer sb = new StringBuffer(bean.getCallPhoneNum());
                sb.insert(3, " ");
                sb.insert(8, " ");
                String s = sb.toString();
                tv_phone_number.setText(s);
            }


            String result = "";

            String address = bean.getCallPhoneAddress();


            if (bean.getHangUpTime() != null && bean.getCallTime() != null) {
                SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");//这个是你要转成后的时间的格式
                String time = sdf.format(new Date(Long.valueOf(bean.getCallTime())));   // 时间戳转换成时间

                result = time + " ";

                long number = (Long.parseLong(bean.getHangUpTime()) - Long.parseLong(bean.getCallTime())) / 1000;
                if (BigDecimalUtil.subtract(new BigDecimal(number), new BigDecimal(60)).intValue() > 0) {
//                System.out.println(number / 60 +1);// 分
                    result = result + "呼出" + (number / 60 + 1) + "分";
                } else {
//                System.out.println(number); //秒
                    result = result + "呼出" + (number) + "秒";

                }
            }


            if (!TextUtils.isEmpty(address)) {
                //            tv_gray.setText("13:03 呼出3分 上海 移动");
                tv_gray.setText(result + " " + address);
            } else {
                tv_gray.setText(result);
            }


            iv_call_right.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(JianpanActivity.this, CallDetailActivity.class);

                    SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");//这个是你要转成后的时间的格式
                    String time = sdf.format(new Date(Long.valueOf(bean.getCallTime())));   // 时间戳转换成时间

                    intent.putExtra("time", String.valueOf(time));
                    intent.putExtra("callPhoneAddress", bean.getCallPhoneAddress());
                    intent.putExtra("callPhoneNum", bean.getCallPhoneNum());
                    startActivity(intent);
                }
            });

//            tv_address.setText(address);
            return holder.getmConvertView();
        }

    }


    @Override
    protected void onResume() {
        super.onResume();
        inputStr = "";
        lv_jianpan.setVisibility(View.VISIBLE);
        tv_input.setVisibility(View.GONE);
        tv_input.setText(inputStr);
        getData();

    }

    private SoundPool soundPool;
    private int soundID;

    @SuppressLint("NewApi")
    private void initSound() {
        soundPool = new SoundPool.Builder().build();
        soundID = soundPool.load(this, R.raw.anjian_music, 1);
    }


    private void playSound() {
        soundPool.play(
                soundID,
                0.5f,      //左耳道音量【0~1】
                0.5f,      //右耳道音量【0~1】
                0,         //播放优先级【0表示最低优先级】
                0,         //循环模式【0表示循环一次，-1表示一直循环，其他表示数字+1表示当前数字对应的循环次数】
                1          //播放速度【1是正常，范围从0~2】
        );
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (soundPool != null) {
            soundPool.release();
            soundPool = null;
        }

    }
}
